from rest_framework import serializers
from typing import List, Tuple, Union
from rest_framework_simplejwt.tokens import RefreshToken, AuthUser, T
from rest_framework_simplejwt.serializers import TokenObtainSerializer, TokenObtainPairSerializer


class DynamicFieldsModelSerializer(serializers.ModelSerializer):
    """
    一个 ModelSerializer，它接受一个额外的 'fields' 参数，该参数
    控制应显示哪些字段。
    """

    def __init__(self, *args, **kwargs):
        fields: Union[List[str], Tuple[str, ...]] = kwargs.pop('fields', [])
        exclude: Union[List[str], Tuple[str, ...]] = kwargs.pop('exclude', [])

        assert not (fields and exclude), "fields 和 exclude 不能同时使用，是互斥的，必须只存在一个"

        super().__init__(*args, **kwargs)

        if fields:
            allowed = set(fields)
            existing = set(self.fields)
            for field_name in existing - allowed:
                self.fields.pop(field_name)

        if exclude:
            for field_name in exclude:
                self.fields.pop(field_name)


class MyRefreshToken(RefreshToken):

    @classmethod
    def for_user(cls: type[T], user: AuthUser) -> T:
        token = super().for_user(user)
        # 添加自定义声明
        token['is_staff'] = user.is_staff
        token['username'] = user.username

        token['name'] = user.name
        if user.clazz:
            token['className'] = user.clazz.name
        else:
            token['className'] = "暂无"

        if user.is_superuser:
            token["roleName"] = "超级管理员"
        elif user.role:
            token["roleName"] = user.role.name
        else:
            token["roleName"] = "普通用户"

        if user.tel:
            # 进行手机号脱敏处理，只显示前三位和后四位数字，中间用****代替
            token["tel"] = user.tel[:3] + "****" + user.tel[-4:]
        else:
            token["tel"] = "暂无"

        return token


# class MyTokenObtainPairSerializer(TokenObtainPairSerializer):
#     @classmethod
#     def get_token(cls, user):
#         token = super().get_token(user)
#
#         # 添加自定义声明
#         token['is_staff'] = user.is_staff
#         token['username'] = user.username
#
#         token['name'] = user.name
#         if user.clazz:
#             token['className'] = user.clazz.name
#         else:
#             token['className'] = "暂无"
#
#         if user.is_superuser:
#             token["roleName"] = "超级管理员"
#         elif user.role:
#             token["roleName"] = user.role.name
#         else:
#             token["roleName"] = "普通用户"
#
#         if user.tel:
#             # 进行手机号脱敏处理，只显示前三位和后四位数字，中间用****代替
#             token["tel"] = user.tel[:3] + "****" + user.tel[-4:]
#         else:
#             token["tel"] = "暂无"
#         # 可以添加更多用户信息...
#
#         return token
